package com.fan.gofast.dao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JSONHandler extends BaseTypeHandler<JSON> {

    public JSON result(String jsonSource) throws SQLException {
        if (jsonSource != null) {
            JSON json;
            try {
                if (JSON.isValidObject(jsonSource)) {
                    json = JSON.parseObject(jsonSource);
                } else {
                    json = JSON.parseArray(jsonSource);
                }
            } catch (JSONException ex) {
                throw new SQLException("There is an error converting JSONObject to json format for the content:" + jsonSource);
            }
            return json;
        }
        return null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, JSON json, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, json.toJSONString());
    }

    @Override
    public JSON getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return result(resultSet.getString(s));
    }

    @Override
    public JSON getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return result(resultSet.getString(i));
    }

    @Override
    public JSON getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return result(callableStatement.getString(i));
    }
}
